rm(list=ls())
library(tidyverse)
library(stringr)

# Create folder to receive data
dir.create(here::here("data","processed","fiscalpolicy"))


# List of files to read
csv_files <- list.files(here::here("data","raw","constitutional_grants"), pattern = ".csv", full.names = T)

# Read data
constitutional_grants <- map(csv_files,
                             read_delim,
                             delim = ";",
                             local = locale(encoding = "latin1"),
                             skip = 1,
                             col_names = c("uf","mun_name","year",
                                           "transfer_type", "total",
                                           "mun_code_ibge", "mun_code_siafi")) %>% 
  bind_rows()

# Format data correctly
constitutional_grants <- constitutional_grants %>% 
  mutate(total = as.numeric(str_replace(str_replace_all(str_replace(total,"R\\$",""),"\\.",""),",",".")),
         mun_code_ibge = str_sub(mun_code_ibge,1,-2))

# Save
write_rds(constitutional_grants,here::here("data","processed","fiscalpolicy","panel_consitutional_grants.rds"))
  
